package com.example.feature;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//前面多个任务都执行完毕，会获取到多个任务的结果来做合并，然后再返回
public class ThenCombineDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        //异步任务1
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("future1:" + Thread.currentThread().getName());
            return "hello";
        }, executorService);
        //异步任务2
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("future2:" + Thread.currentThread().getName());
            return "hello2";
        }, executorService);

        //任务1 连接任务2  同时传递 两个任务的返回值作为参数传递
        CompletableFuture<String> res = future1.thenCombineAsync(future2, (r1, r2) -> {
            System.out.println("combine future3:" + Thread.currentThread().getName());
            return r1 + r2;
        }, executorService);

        System.out.println(res.get());

        executorService.shutdown();

    }
}
